<template>
    <div class="">
        <div class="float_left tree_box">
            <h4 class="margin_bottom20">菜单结构</h4>
            <div class="clear"></div>
            <el-tree :data="treeJson"
                    node-key="id"
                    :props="defaultProps"
                    :expand-on-click-node="true"
                    @current-change="currentChange"
                    highlight-current
                    :current-node-key="selectedMenu.id"
                    >
            </el-tree>
        </div>
        <div class="operate_main">
            <h4 class="margin_bottom20">菜单列表</h4>
            <el-form :inline="true" :model="selectedMenu" class="demo-form-inline">
                <el-form-item label="菜单名">
                    <el-input v-model="selectedMenu.menuName" placeholder="菜单名" size="small"></el-input>
                </el-form-item>
                <el-form-item label="url">
                    <el-input v-model="selectedMenu.url" placeholder="菜单URL" size="small" style="width:400px;"></el-input>
                </el-form-item>
                <br/>
                <el-form-item label="显示顺序">
                    <el-input v-model="selectedMenu.display" placeholder="显示顺序" size="small" style="width:50px;"></el-input>
                </el-form-item>
                <el-form-item label="显示图标">
                    <el-input v-model="selectedMenu.menuIco" placeholder="icon值" size="small" style="width:80px;"></el-input>
                </el-form-item>
                <el-form-item style="vertical-align: bottom">
                    <el-button type="primary" size="small" @click="update" :disabled="selectedMenu.currLevel == 0">保存修改</el-button>
                </el-form-item>
                <el-form-item style="vertical-align: bottom">
                    <el-button type="success" size="small" @click="addChild" :disabled="selectedMenu.currLevel == 0">添加子菜单</el-button>
                </el-form-item>
                <el-form-item style="vertical-align: bottom">
                    <el-button type="success" size="small" @click="addBrother" :disabled="selectedMenu.currLevel == 0">添加同级菜单</el-button>
                </el-form-item>

                <!-- <el-form-item style="vertical-align: bottom">
                    <el-button type="warning" size="small" @click="changeRole" :disabled="selectedMenu.currLevel == 0">修改权限</el-button>
                </el-form-item> -->
                <el-form-item style="vertical-align: bottom">
                    <el-button type="danger" size="small" @click="deleteRow(selectedMenu.id)" :disabled="selectedMenu.currLevel == 0">删除此菜单</el-button>
                </el-form-item>
            </el-form>
            <template>
                <el-table :data="tableData" border style="width: 100%">
                    <el-table-column header-align="center" type="selection" width="55"> </el-table-column>
                    <el-table-column header-align="center" prop="menuName" label="菜单名"></el-table-column>
                    <el-table-column header-align="center" prop="url" label="url"></el-table-column>
                    <el-table-column header-align="center" label="操作" width="150">
                        <template slot-scope="scope">
                            <el-button @click="edit(tableData[scope.$index])" type="text" size="small">编辑</el-button>
                            <el-button @click.native.prevent="deleteRow(tableData[scope.$index].id)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </div>

        <!-- 表单弹窗 -->
        <el-dialog title="编辑子菜单" v-model="dialogFormVisible">
            <el-form :model="menu" ref="menuForm">
                <el-form-item label="菜单名称" :label-width="formLabelWidth" prop="menuName"
                    :rules="[{ required: true, message: '菜单名不能为空'}]">
                    <el-input v-model="menu.menuName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="url" :label-width="formLabelWidth" prop="url" >
                    <el-input v-model="menu.url" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="菜单级别" :label-width="formLabelWidth">
                    {{menu.currLevel}}
                </el-form-item>
                <el-form-item label="上级菜单" :label-width="formLabelWidth">
                    {{menu.parentMenuName}}
                </el-form-item>
                <el-form-item label="显示图标" :label-width="formLabelWidth" prop="menuIco">
                    <el-input v-model="menu.menuIco" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="显示顺序" :label-width="formLabelWidth" prop="display" :rules="[{ required: true, message: '显示顺序不能为空'}]">
                    <el-input v-model="menu.display" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addMenu">确 定</el-button>
            </div>
        </el-dialog>

        
        <!-- 权限分配页面dialog -->
        <el-dialog title="该菜单可分配角色" v-model="dialogRoleVisible">
            <el-card class="box-card">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0;"></div>

                <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRoleChange">
                    <el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{{role.roleName}}</el-checkbox>
                </el-checkbox-group>
            </el-card>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveMenuRole">确 定</el-button>
            </div>
        </el-dialog>

        <div class="clear"></div>

    </div>
</template>
<script>
    let id = 1000;

    export default {
        name:'app',
        data() {
            return {
                treeJson: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                tableData: [],
                menu: {
                    id: '',
                    menuName: '',
                    url: '',
                    currLevel: 0,
                    display: 0,
                    menuIco: '',
                    parentMenuName: '',
                    parentId: ''
                },
                selectedMenu: '',
                dialogFormVisible: false,
                formLabelWidth: '120px',

                //分配角色时候用的数据
                dialogRoleVisible: false,
                checkAll: true,
                checkedRoles: [],
                roles: '',
                isIndeterminate: true           
            }
        },
    methods: {

        //点击左侧的菜单树的时候进行查询本菜单数据以及修改显示右侧的儿子级所有菜单
        currentChange(data, node) {
            this.$http.get(API.menu, {params: {id: data.id}}).then((response) => {
                console.log(response.body.data);

                this.selectedMenu = response.body.data.menu;
                this.tableData = response.body.data.children;
            }, (response) => {
                // error callback
            }); 

        },

        //修改菜单的基本信息
        update() {
            this.$http.put(API.menu, this.selectedMenu, {emulateJSON: false}).then((response) => {

                if(response.body.status == 0) {
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        customClass: 'messageDIY'
                    });
                }
            });
        },

        //添加子菜单，弹出dialog
        addChild() {
            this.dialogFormVisible = true;
            this.menu.parentId = this.selectedMenu.id;
            this.menu.parentMenuName = this.selectedMenu.menuName;
            this.menu.currLevel = this.selectedMenu.currLevel + 1;
        },

        //添加兄弟菜单，弹出dialog
        addBrother() {
            this.dialogFormVisible = true;
            this.menu.parentId = this.selectedMenu.parentId;
            this.menu.parentMenuName = this.selectedMenu.parentMenuName;
            this.menu.currLevel = this.selectedMenu.currLevel;
        },

        //添加子菜单的保存方法
        addMenu() {
            this.$http.post(API.menu, this.menu, {emulateJSON: false}).then((response) => {

                if(response.body.status == 0) {
                    this.$message({
                        message: '保存成功',
                        type: 'success',
                        customClass: 'messageDIY'
                    });

                    //重置表单，其实就是将表单的内容设置为空
                    this.$refs['menuForm'].resetFields();

                    //关闭添加窗口
                    this.dialogFormVisible = false;
                    this.$http.get(API.menuTree + "/" + localStorage.userId).then((response) => {
                        // console.log(response.body.data);

                        this.treeJson = response.body.data;
                    });
                    this.$http.get(API.menu, {params: {id: this.selectedMenu.id}}).then((response) => {

                        this.selectedMenu = response.body.data.menu;
                        this.tableData = response.body.data.children;
                    }, (response) => {
                        // error callback
                    }); 
                }
            });
        },

        edit(menu) {
            //浅拷贝，将选中的某行的menu赋值给menu，修改之后会影响这条被选中的menu
            this.menu = menu;

            //打开新增和编辑的窗口
            this.dialogFormVisible = true;
        },

        deleteRow(id) {
            this.$confirm('确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                this.$http.delete(API.menu, {params:{id: id}}).then((response) => {

                    //返回值是0的时候表示成功,重新加载数据
                    if(response.body.status == 0) {

                        //删除成功之后重新加载数据
                        this.$http.get(API.menuTree + "/" + localStorage.userId).then((response) => {

                            this.treeJson = response.body.data;
                        });

                        this.selectedMenu = {
                            id: '',
                            menuName: '',
                            url: '',
                            currLevel: 0,
                            display: 0,
                            menuIco: '',
                            parentMenuName: '',
                            parentId: ''
                        };
                        this.tableData = [];
                        // this.currentChange(this.selectedMenu, null);
                    }
                }, (response) => {
                    // error callback
                }); 
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });            
        },

        //点击修改权限,弹出框，并且赋值上已经勾选的角色
        changeRole() {
            this.dialogRoleVisible = true;

            this.$http.get(API.getRoleList, {params: {}}).then((response) => {
 
                this.roles = response.body.data;
            }, (response) => {
                // error callback
            });

            //查询已经勾选的角色的数据请求，根据当前选中的菜单，获取拥有此菜单的角色
            this.$http.get(API.menu + "/" + this.selectedMenu.id + "/roles", {params: {}}).then((response) => {
                this.checkedRoles = response.body.data;
            }, (response) => {
                // error callback
            });

        },

        //分配菜单给角色时候的全选
        handleCheckAllChange(event) {

            //如果勾选的是全部选中
            if(event.target.checked) {
                for (var i in this.roles) {
                    // console.log(this.roles[i].id);
                    this.checkedRoles.push(this.roles[i].id);
                } 
                // console.log(this.checkedRoles);              
            } else {
                this.checkedRoles = [];
            }

            this.isIndeterminate = false;
        },

        //选中一个角色的时候
        handleCheckedRoleChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.roles.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
        },

        //保存菜单和角色的关系
        saveMenuRole() {
                var roleIds = new Array();
                for (var i = 0; i < this.checkedRoles.length; i++) {
                    let roleId = this.checkedRoles[i];
                    roleIds.push(roleId);
                }

            this.$http.post(API.menu + "/" + this.selectedMenu.id + "/roles", {roleIds: roleIds.join(",")}, {emulateJSON: true}).then((response) => {
                // console.log(response.body.data);

                if(response.body.status == 0) {
                    this.$message({
                        message: '添加成功',
                        type: 'success',
                        customClass: 'messageDIY'
                    });

                    this.dialogRoleVisible = false;
                }
            });
        }
    },
    created() {
        this.selectedMenu = this.menu;
        this.$http.get(API.menuTree + "/" + localStorage.userId).then((response) => {
            // console.log(response.body.data);

            this.treeJson = response.body.data;
        }, (response) => {
            // error callback
        }); 
    }
};
</script>

